package com.tuanzi.loan.web.bean.channel;

import com.google.common.collect.Lists;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import com.tuanzi.loan.business.entity.common.CommProductId;
import com.tuanzi.loan.business.service.common.CommProductIdService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.web.configuration.JSFInfoBean;
import com.tuanzi.server.loan_base.constant.LoanRedisKey;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.event.FileUploadEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.List;

import static com.tuanzi.loan.business.constants.DictionaryCode.LARGE_COMMON_PRODUCT;

/**
 * @author caiwanlin
 * @create 2018-10-18 14:34
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class CommProductIdInfoBean extends JSFInfoBean<CommProductId> {
    @Autowired
    private CommProductIdService commProductIdService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    private void init() {
        //生效时间设置
        String id = getParamFromRequest("id");
        if (StringUtils.isNotBlank(id)) {
            $ = commProductIdService.findOne(Long.parseLong(id));
        } else {
            $ = new CommProductId();
            changeStatusToAdd();
        }
    }

    public void onSave(){
        try {
            commProductIdService.saveOrUpdate($);
            stringRedisTemplate.delete(LoanRedisKey.GET_PRODUCT_BY_PRODID + $.getProductId());
        } catch (Exception e) {
            if (e.getCause().getCause() instanceof MySQLIntegrityConstraintViolationException){
                addErrorMessage("产品ID重复");
                return;
            }
        }
        addSuccessfullyMessage();
        changeStatusToView();
    }

    public void onUploadExtraLogo(FileUploadEvent event) {
        $.setExtraLogo(this.uploadImg(event.getFile()));
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(LARGE_COMMON_PRODUCT);
    }
}
